<?php

function _url_for($options = Array())
{
	$action = "main";
	$qs = "";

	if (count($options) > 1) {
		while (list($key, $val) = each($options)) {
			switch ($key) {
				case "controller":
					$controller = $val;
					break;
				case "action":
					$action = $val;
					break;
				default:
					if (!empty($key))
						$qs .= "&$key=$val";
					else
						$qs .= "$val/";
			}
		}
	}

	if (Session::$mod_rewrite && preg_match("/\bdispatch.php\b/", $_SERVER["PHP_SELF"])) {
		if (empty($controller)) {
			$controller = Session::$controller;
		}

		if (!empty($qs) && strstr($qs, "=") && strstr($qs, "&")) $qs = "?$qs";

		return "http://" . $_SERVER["SERVER_NAME"] . Cabbie::$url_prefix . "/$controller/$action/$qs";
	}

	if (empty($controller))
		$controller = Session::$controller;

	return "http://" . $_SERVER["SERVER_NAME"] . Cabbie::$url_prefix . "/dispatch.php?controller=$controller&action=$action$qs";
}

function _image_tag($image, $options = array())
{
	$attributes = "";

	$options["src"] = Cabbie::$url_prefix . $image;
	if (array_key_exists("size", $options)) {
		$size = explode("x", $options["size"]);
		$options["width"] = $size[0];
		$options["height"] = $size[0];
		$options = array_delete($options, "size");
	}

	return tag("img", $options);
}

function image_to($image, $link, $options = array())
{
    $image = image_tag($image, $options);
    $url = link_to($image, $link, $options);
    return $url;
}

/**
 * get_uri_assoc()
 *   return an associative array for the uri parameters.
 * 	e.g. /members/user/reno/foto/14 will return an
 *   array in the form:
 *   array (
 *   "user" => "reno",
 *   "foto" => 14)
 *   if there is no params available, this function will return false.
 *
 * @var NULL
 * @return Array
 */

function get_uri_assoc()
{
	$params = Cabbie::$uri_params;

	if (count($params) >= 2) {
		$assoc = Array();
		for($q = 0;$q < count($params);$q = $q + 2) {
			$assoc[$params[$q]] = $params[$q + 1];
		}
	} else return false;
	return $assoc;
}

/**
 * get_uri_obj()
 *   return an object with the uri parameters in the form of key->value.
 * 	e.g. /members/user/reno/foto/14 will return an
 *   object in the form:
 *   $return object {
 * 	 user : reno;
 *   foto : 14 )
 *   if there is no params available, this function will return false.
 *
 * @var NULL
 * @return Object
 */

function get_uri_obj()
{
	$params = Cabbie::$uri_params;

	if (count($params) >= 2) {
		for($q = 0;$q < count($params);$q = $q + 2) {
			$assoc->$params[$q] = $params[$q + 1];
		}
	} else return false;
	return $assoc;
}

/**
 * group_uri_key()
 * tests for a key/value pair in the uri params
 * and, if found, returns a string in the form of /key/value.
 * if there is no params available, of the given key is not found,
 * this function will return false.
 *
 * @var searchkey
 * @return String
 */

function group_uri_key($testvalue)
{
	$params = Cabbie::$uri_params;

	if (count($params) >= 2) {
		for($q = 0;$q < count($params);$q = $q + 2) {
			if($params[$q] == $testvalue) return "/".$params[$q]."/".$params[$q + 1];
		}
	} else return false;

}



function _link_to($label, $link, $options = array())
{
	$attributes = "";

	if (array_key_exists("confirm", $options)) {
		$options["onClick"] = "return confirm('" . addslashes($options["confirm"]) . "') ";
		$options = array_delete($options, "confirm");
	}

	if (is_string($link))
		$options["href"] = $link;
	else if (is_array($link))
		$options["href"] = url_for($link);

	return content_tag("a",
		$label,
		$options);
}

function _form_tag($link = "", $options = array())
{
	if (is_array($link) && count($link) > 0)
		$action = url_for($link);
	else
		$action = url_for(array("controller" => Session::$controller,
				"action" => Session::$action));

	$options["method"] = "post";
	$options["action"] = $action;

	return tag("form",
		$options,
		true);
}

function _end_form_tag()
{
	return "</form>";
}

function _text_field_tag($name, $value = "", $options = array())
{
	if (!isset($options["type"]))
		$options["type"] = "text";
	$options["value"] = $value;
	$options["name"] = $name;
	$options["id"] = $name;
	return tag("input", $options);
}

function _hidden_field_tag($name, $value = "", $options = array())
{
	$options["type"] = "hidden";
	return text_field_tag($name, $value, $options);
}

function _submit_tag($value = "Save changes", $options = array())
{
	if (array_key_exists("confirm", $options)) {
		$options["onClick"] = "return confirm('" . addslashes($options["confirm"]) . "') ";
		$options = array_delete($options, "confirm");
	}

	$options["type"] = "submit";
	$options["value"] = $value;
	if (!$options["name"])
		$options["name"] = "commit";
	return tag("input", $options);
}

function _stylesheet_link_tag($file, $options = array())
{
	if (!array_key_exists("media", $options))
		$options["media"] = "screen";

	$options["href"] = "http://" . $_SERVER["SERVER_NAME"] . Cabbie::$url_prefix . "/stylesheets/$file.css";
	$options["rel"] = "Stylesheet";
	$options["type"] = "text/css";

	return tag("link", $options);
}

function _javascript_include_tag($js)
{
	if ($js[0] == "/")
		$js = Cabbie::$url_prefix . "$js.js";
	else
		$js = Cabbie::$url_prefix . "/javascripts/$js.js";

	return content_tag("script",
		"",
		array("type" => "text/javascript",
			"src" => $js));
}

function render($options = array())
{
	$ac = new ActionController();
	$ac->render($options);
}

function render_partial($options)
{
	if (!is_array($options))
		return false;

	$partial = "";
	$collection = "";

	while (list($key, $val) = each($options)) {
		switch ($key) {
			case "partial":
				$partial = $val;
				break;

			case "collection":
				$collection = $val;
				break;

			case "locals":
				if (!is_array($options["locals"]))
					break;
				foreach($options["locals"] as $tmp_key => $tmp_value) {
					${$tmp_key} = $tmp_value;
				}
				unset($tmp_key);
				unset($tmp_value);
				break;
		}
	}

	if (strstr($partial, '/'))
		list($controller, $partial) = explode('/', $partial);
	else
		$controller = Session::$controller;

	$view = Cabbie::$approot . "/views/" . $controller . "/_$partial.php";
	if (file_exists($view)) {
		ob_start();
		$counter = $partial . "_counter";
		$$counter = 0;
		foreach($collection as $$partial) {
			include $view;
			++$$counter;
		}
		unset($$counter);
		return ob_get_clean();
	}
	return false;
}

function render_full($options)
{
	if (!is_array($options))
		return false;

	$partial = "";
	$collection = "";

	while (list($key, $val) = each($options)) {
		switch ($key) {
			case "action":
				$view = $val;
				break;

			case "controller":
				$controller = $val;
				break;

			case "collection":
				$collection = $val;
				break;

			case "locals":
				if (!is_array($options["locals"]))
					break;
				foreach($options["locals"] as $tmp_key => $tmp_value) {
					${$tmp_key} = $tmp_value;
				}
				unset($tmp_key);
				unset($tmp_value);
				break;
		}
	}
	include_once(Cabbie::$approot . "/controllers/" . $controller . "_controller.php");
	$data = $controller . "Controller" . "::" . $view . "();";
	eval($data);
	$view = Cabbie::$approot . "/views/" . $controller . "/$view.php";
	if (file_exists($view)) {
		ob_start();
		foreach($collection as $$action)
		include $view;
		return ob_get_clean();
	}

	return false;
}

function translate($content)
{
	if (!file_exists(Cabbie::$approot . "/languages/" . Cabbie::$language . ".php"))
		return $content;

	include(Cabbie::$approot . "/languages/" . Cabbie::$language . ".php");
	$class = Cabbie::$language . "_Language";
	$l = new $class();

	$output = $content;

	for($i = 0; $i < strlen($content); $i++) {
		$id = "";

		if ($content[$i] == "<" && $content[$i + 1] == "t" && $content[$i + 2] == "r" && $content[$i + 3] == "n") {
			$j = $i + 4;
			if ($content[$j] != " ")
				continue;

			while ($content[$j] == " ")
			$j++;

			if ($content[$j] != "i")
				continue;

			if ($content[$j + 1] != "d")
				continue;

			if ($content[$j + 2] != " " && $content[$j + 2] != "\"" && $content[$j + 2] != "'" && $content[$j + 2] != "=" && !is_numeric($content[$j + 2]))
				continue;

			$j += 2;
			while ($content[$j] == " ")
			$j++;

			if ($content[$j++] != "=")
				continue;

			while ($content[$j] == " ")
			$j++;

			if ($content[$j] != "\"" && $content[$j] != "'" && !is_numeric($content[$j + 2]))
				continue;

			$quotes = array("\"", "'");

			foreach($quotes as $quote) {
				if ($content[$j] == $quote) {
					$j++;

					while ($content[$j] == " ")
					$j++;

					if (!is_numeric($content[$j]))
						continue;

					while (is_numeric($content[$j])) {
						$id .= $content[$j];
						$j++;
					}

					if ($content[$j] != " " && $content[$j] != $quote)
						continue;

					while ($content[$j] == " ")
					$j++;

					if ($content[$j] != $quote)
						continue;

					$j++;

					if ($content[$j] != " " && $content[$j] != "/" && $content[$j] != ">")
						continue;

					while ($content[$j] == " ")
					$j++;

					if ($content[$j] != "/" && $content[$j] != ">")
						continue;

					if ($content[$j] == "/" && $content[$j + 1] != ">")
						continue;
					else
					if ($content[$j + 1] == ">")
						$j++;
					else if ($content[$j] != ">")
						continue;
					// $j++;
					while (substr($content, $j, 5) != "</trn" && $j < strlen($content))
					$j++;

					$j += 5;

					if ($content[$j] != " " && $content[$j] != "/" && $content[$j] != ">")
						continue;

					while ($content[$j] == " ")
					$j++;

					if ($content[$j] != "/" && $content[$j] != ">")
						continue;

					if ($content[$j] == "/" && $content[$j + 1] != ">")
						continue;
					else if ($content[$j + 1] == ">")
						$j++;
					else if ($content[$j] != ">")
						continue;

					$output = str_replace(substr($content, $i, $j - $i + 1), $l->tr[$id], $output);
				}
			}
		}
	}
	return $output;
}

function _auto_discovery_link_tag($type, $url_options, $tag_options = array())
{
	return
	tag("link",
		array("rel" => $type,
			"type" => array_key_exists("type", $tag_options) ? $tag_options["type"] : "application/$type+xml",
			"title" => array_key_exists("title", $tag_options) ? $tag_options["title"] : strtoupper($type),
			"href" => url_for($url_options)
			)
		);
}

function _tag($name, $tag_options = array(), $open = false)
{
	$options = "";
	while (list($key, $val) = each($tag_options))
	$options .= " $key=\"$val\"";

	return "<$name$options " . ($open ? ">" : "/>");
}

function _content_tag($name, $content = "", $options = array())
{
	return tag($name, $options) . $content . "</$name>";
}

function jquery_tag($name,$url,$target,$tag_options=array())
{
	$options = "";
	while (list($key, $val) = each($tag_options))
		$options .= " $key=\"$val\"";
	return "<a $options href=\"javascript:void(0);\" onclick=\"$('#$target').load('$url');return false;\">$name</a>";
}

function _raw_post_data()
{
	$data = file_get_contents("php://input");

	if (strstr($data, "&_="))
		$data = explode("&_=", $data);
	$data = is_array($data) ? $data[0] : $data;
	return $data;
}

/**
 * STUFF ABOVE THIS IS DEPRECATED
 */

function redirect_to()
{
	$arg_list = func_get_args();
	if (is_string($arg_list[0]))
		header("Location: $arg_list[0]");
	else if (is_array($arg_list[0])) {
		$url = url_for($arg_list[0]);
		header("Location: $url");
	}
	exit();
	/* we need to exit to terminate php's current request */
}

/*
 * Xml - An xml writer class that can also make use of Tidy for formatting
 */

class Xml {
	static private $indent = 0;
	static private $stack = array();

	function __construct()
	{
	}

	private function __call($method, $arguments)
	{
		$tag = $method;
		$options = "";
		$value = "";
		if (is_array($arguments) && count($arguments) > 0) {
			if (is_array($arguments[0])) {
				while (list($key, $val) = each($arguments[0]))
				$options .= " $key=\"$val\"";
			} else
				$value = $arguments[0];

			if (count($arguments) > 1) {
				for($i = 1; $i < count($arguments); $i++) {
					$value .= $arguments[$i];
				}
			}
		}

		$xml = "\n<$tag$options>$value</$tag>\n";
		return $xml;
	}

	private function indent($spaces)
	{
		$indent = "";
		for($i = 0; $i < $spaces; $i++)
		$indent .= " ";
		return $indent;
	}

	public function tidy($xml)
	{
		if (!class_exists("tidy"))
			return $xml;

		$config = array('indent' => true, "input-xml" => true);
		$tidy = new tidy();
		$tidy->parseString($xml, $config, 'utf8');
		$tidy->cleanRepair();
		return $tidy;
	}

	public function instruct($fields)
	{
		$value = "";

		if (!is_array($fields))
			$value = "$fields";
		else
			while (list($key, $val) = each($fields)) {
			if ($key && $val)
				$value .= "$key=\"$val\" ";
			else if ($val)
				$value .= "$val ";
		}

		return "\n<?$value?>\n";
	}
}

?>